package walasp.proto;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**
 * 
 * Activity for viewing the full list of Tasks.
 * 
 */
public class TaskListActivity extends ListActivity {
	
	//the context used by TaskHelper
	public static Context firstContext;
	
	//the helper used for accessing the Tasks Database
	TaskHelper helper;
	
	//ArrayList used by the Custom ArrayAdapter
	ArrayList<Task> tasks;
	//Custom ArrayAdapter used by the ListActivity
	TaskAdapter TaskADPT;

	/**
	 * Initializes the ListsActivitys ArrayAdapter. Does the Initial Population
	 * of the List Sets the Onclick and OnLongClick listeners
	 * 
	 * @param savedInstanceState
	 *            The saved instance state
	 */
	public void onCreate(Bundle savedInstanceState) {

		// call the super constructor as required
		super.onCreate(savedInstanceState);
		// set the context used for various helpers
		firstContext = this;
		// get our helper
		helper = new TaskHelper(firstContext);
		// get the task list used for the TaskAdapter
		tasks = helper.getAllTasks();
		// finished with helper now
		helper.close();

		// create the TaskAdapter(a custom ArrayAdapte Class), using the
		// tasklist layout, the tasks AarrayList and this activity's context
		TaskADPT = new TaskAdapter(this, R.layout.tasklist, tasks);

		// get the inflater for the header
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// inflate the header
		View header = inflator.inflate(R.layout.listheader, null);

		// get this ListActivitys list view
		ListView listy = getListView();
		// set the lists context menus(used for long clicks)
		registerForContextMenu(listy);

		// add the header to the listview
		listy.addHeaderView(header);

		// set the list views adapter
		setListAdapter(TaskADPT);

		// set the headers on click to open the edit activity
		header.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent newTaskintent = new Intent(firstContext,
						EditActivity.class);

				startActivityForResult(newTaskintent, 0);

			}
		});

		// set every other items on click listener to open the task view for the
		// selected item
		listy.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int _position, long id) {
				// decrement this because of the header
				int position = _position - 1;

				Intent intent = new Intent(firstContext, ViewActivity.class);
				intent.putExtra("TID", tasks.get(position).getTID());
				startActivity(intent);
			}
		});

	}

	@Override
	public void onResume() {
		/*
		 * Ensures task list updates after a task has been updated, since
		 * changes to the ArrayList instance don't automatically propagate
		 */
		helper = new TaskHelper(firstContext);

		ArrayList<Task> freshTasks = helper.getAllTasks();
		for (Task f : freshTasks) {
			boolean found = false;
			for (Task t : tasks) {
				if (t.getTID() == f.getTID()) {
					// ensure the displayed data is updated
					t.setDueDate(f.getDueDate());
					t.setTaskName(f.getTaskName());
					//notify the adapter of an updated dataset
					TaskADPT.notifyDataSetChanged();

					found = true;
				}
			}
			if (found == false) {
				// add any new task
				tasks.add(f);
				//notify the adapter of an updated dataset
				TaskADPT.notifyDataSetChanged();
			}
		}
		// done with helper now
		helper.close();
		// call super function as required
		super.onResume();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		info.position = info.position - 1;
		menu.setHeaderTitle(tasks.get(info.position).getTaskName());
		String[] menuItems = getResources().getStringArray(R.array.contextMenu);
		for (int i = 0; i < menuItems.length; i++) {
			menu.add(Menu.NONE, i, i, menuItems[i]);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();

		/*
		 * what to do if the 1st context menu item is pressed VIEW
		 */
		if (menuItemIndex == 0) {
			Intent intent = new Intent(firstContext, ViewActivity.class);
			intent.putExtra("TID", tasks.get(info.position).getTID());
			startActivity(intent);
			/*
			 * Toast.makeText( getApplicationContext(), "View " +
			 * String.valueOf(tasks.get(info.position).getTID()),
			 * Toast.LENGTH_LONG).show();
			 */
		}

		/*
		 * what to do if the 2nd context menu item is pressed EDIT
		 */
		if (menuItemIndex == 1) {
			Intent intent = new Intent(firstContext, EditActivity.class);
			intent.putExtra("mode", 1);
			intent.putExtra("TID", tasks.get(info.position).getTID());
			startActivity(intent);
		}

		/*
		 * what to do if the 3rd context menu item is pressed DELETE
		 */
		if (menuItemIndex == 2) {
			int TIDDelete = tasks.get(info.position).getTID();
			helper = new TaskHelper(firstContext);
			helper.deleteTask(TIDDelete);
			tasks.remove(info.position);
			helper.close();

			TaskADPT.notifyDataSetChanged();
		}

		// active
		if (menuItemIndex == 3) {
			tasks.get(info.position).setStatus(Status.ACTIVE);
			TaskADPT.notifyDataSetChanged();
		}
		// completed
		if (menuItemIndex == 4) {
			tasks.get(info.position).setStatus(Status.FINISHED);
			TaskADPT.notifyDataSetChanged();
		}
		// cancelled
		if (menuItemIndex == 5) {
			tasks.get(info.position).setStatus(Status.CANCELLED);
			TaskADPT.notifyDataSetChanged();
		}

		return true;
	}

}
